package com.tanhua.server.service;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.model.domain.Question;
import com.itheima.model.domain.Settings;
import com.itheima.model.domain.User;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.tanhua.sso.vo.ErrorResult;
import com.itheima.model.vo.PageResult;
import com.itheima.model.vo.SettingsVo;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Map;

@Slf4j
@Service
public class SettingsService {

    @DubboReference
    private SettingsApi settingsApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserApi userApi;

    //查询通用设置
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        vo.setId(userId);

        //2、获取用户的手机号码
        vo.setPhone(UserHolder.getMobile());

        //4、 获取用户的通知开关数据
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }
        return vo;
    }

    public Question question() {
        Question vo = new Question();
        //1、获取用户id
        Long userId = UserHolder.getUserId();

        vo.setId(userId);
        Question question = settingsApi.question(userId);
        String txt = question == null ? "你喜欢java吗？" : question.getTxt();
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setStrangerQuestion(txt);
        return question;
    }

    /**
     * 设置陌生人问题
     *
     * @param content
     */
    public void saveQuestion(String content) {
        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用api查询当前用户的陌生人问题
        Question question = settingsApi.question(userId);
        //3、判断问题是否存在

        if (question == null) {
            //3.1、如果不存在
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            settingsApi.save(question);
        } else {
            //3.2、如果存在更新
            question.setTxt(content);
            settingsApi.update(question);
        }
    }

    /**
     * 设置通知设置
     *
     * @param map
     */
    public void saveSettings(Map map) {

        boolean likeNotification = (Boolean) map.get("likeNotification");
        boolean pinglunNotification = (Boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (Boolean) map.get("gonggaoNotification");
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询用户的通知设置
        Settings settings2 = settingsApi.findByUserId(userId);
        //3、判断
        if (settings2 == null) {
            //保存
            settings2 = new Settings();
            settings2.setUserId(userId);
            settings2.setPinglunNotification(pinglunNotification);
            settings2.setLikeNotification(likeNotification);
            settings2.setGonggaoNotification(gonggaoNotification);
            settingsApi.save2(settings2);
        } else {
            settings2.setPinglunNotification(pinglunNotification);
            settings2.setLikeNotification(likeNotification);
            settings2.setGonggaoNotification(gonggaoNotification);
            settingsApi.update2(settings2);
        }

    }

    public PageResult blacklist(int page, int size) {

        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询用户的黑名单分页列表  Ipage对象
        IPage<UserInfo> iPage = settingsApi.blackFindByUserId(userId, page, size);
        //3、对象转化，将查询的Ipage对象的内容封装到PageResult中
        PageResult pr = new PageResult(page, size, iPage.getTotal(), iPage.getRecords());
        //4、返回
        return pr;
    }

    //取消黑名单
    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        settingsApi.deleteBlackList(userId, blackUserId);
    }

    public void sendVerification() {
        String mobile = UserHolder.getMobile();

        String code = "123456";
        log.info("mobile:{}, code:{}), mobile, code");
        redisTemplate.opsForValue().set("Verification_Code_" + mobile, code, Duration.ofMinutes(5L));
    }

    //校验验证码
    public Boolean checkVerification(String verificationCode) {
        String mobile = "Verification_Code_" + UserHolder.getMobile();
        String codeInRedis = (String) redisTemplate.opsForValue().get(mobile);
        if (StringUtils.isEmpty(codeInRedis) || !verificationCode.equals(codeInRedis)) {
            redisTemplate.delete(mobile);
        }
        return true;
    }

    //更改手机号
    public void phone(String phone) {
        User user = settingsApi.isMobileExit(phone);
        if (user != null) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        user = UserHolder.get();
        user.setMobile(phone);
        userApi.updateById(phone);
    }
}
